package com.euq.service.Impl;

import com.euq.dto.*;
import com.euq.entity.User;
import com.euq.enums.UserStatus;
import com.euq.mapper.UserMapper;
import com.euq.service.UserService;
import com.euq.utils.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;


import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public Object login(String account, String password) throws Exception {
        UserParam.paramValidate(account, password);
        User user = userMapper.findByAccount(account);
        UserParam.businessValidate(user,account);
        String token = JwtUtils.generateToken(account);
        return new AuthResponse(token, user);
    }

    @Override
    @CacheEvict(value = "userCache", allEntries = true)
    public Object register(User user) throws Exception {
        if(userMapper.findByAccount(user.getAccount())!=null){throw new RuntimeException("账号已存在");}
        user.setSalt(MD5.generateSalt());
        user.setPassword(MD5.md5(user.getPassword(),user.getSalt()));
        user.setStatus(UserStatus.ACTIVE.getValue());
        user.setVersion(2);
        userMapper.insert(user);
        return null;
    }

    @Override
    public ResponseEntity<?> getUserInfo() {
        LoginUser loginUser = SecurityUtils.getCurrentUser();
        User user = loginUser.getUser();
        user.setPassword(null);
        return ResponseEntity.ok(Ret.success(user));
    }

    @Override
    @CacheEvict(value = "userCache", allEntries = true)
    public Object updatePwd(String oldPwd, String newPwd, String rePwd) throws Exception {
        UserParam.PwdValidate(oldPwd,newPwd,rePwd);
        LoginUser loginUser = SecurityUtils.getCurrentUser();
        User user = loginUser.getUser();
        if (user.getId()==1){throw new RuntimeException("不能修改超级管理员密码");}
        if (!MD5.md5(oldPwd,user.getSalt()).equals(user.getPassword())) {throw new RuntimeException("旧密码错误");}
        user.setPassword(MD5.md5(newPwd,user.getSalt()));
        userMapper.update(user);
        return Ret.success("密码修改成功");
    }

    @Override
    public PageInfo<User> getUsers(int page, int size) {
        PageHelper.startPage(page, size);
        List<User> users = userMapper.listAll();
        return new PageInfo<>(users);
    }

    @Override
    @Cacheable(
            value = "userCache",
            key = "T(String).format('%s:%d:%d:%s:%s', #account, #page, #size, #status, #name)"
    )
    public PageInfo<UserDTO> selectUsers(int page, int size, String account, String status, String name) {
        PageHelper.startPage(page, size);
        List<User> users = userMapper.selectByConditions(account, status, name);
        List<UserDTO> userDTOs = UserConverter.toDTOList(users);
        return new PageInfo<>(userDTOs);
    }

    @Override
    public String findByAccountV2(String account, String password) throws Exception {
        // 参数校验
        UserParam.paramValidate(account, password);

        // 数据查询
        User user = userMapper.findByAccount(account);

        // 业务验证
        UserParam.businessValidate(user, account);

        // 生成token
        String token = JwtUtils.generateToken(account);

        return token;
    }

    @Override
    @CacheEvict(value = "userCache", allEntries = true)
    public User update(User user) {
        try{
            userMapper.update(user);
            return user;
    }catch (Exception e) {throw new RuntimeException("更新用户失败", e);}
    }

    @Override
    @CacheEvict(value = "userCache", allEntries = true)
    public Object deleteById(Long id) throws Exception {
        UserParam.idValidate(id);
        User user = userMapper.findById(id);
        if (user==null){throw new RuntimeException("删除用户失败");}
        user.setStatus(3);
        userMapper.update(user);
        return null;
    }

    @Override
    @CacheEvict(value = "userCache", allEntries = true)
    public Object changeStatus(Long id, long status) throws Exception {
        UserParam.userStatusValidate(id,status);
        User user =userMapper.findById(id);
        if (user == null) {throw new RuntimeException("冻结/解冻失败");}
        user.setStatus(status);
        userMapper.update(user);
        return Ret.success("操作成功");
    }

    @Override
    @CacheEvict(value = "userCache", allEntries = true)
    public Object resetPassword(Long id) throws Exception {
        User user =userMapper.findById(id);
        if (user == null) {throw new RuntimeException("重置密码失败");}
        user.setPassword(MD5.md5("123456",user.getSalt()));
        userMapper.update(user);
        return Ret.success("密码重置成功");
    }

    @Override
    @CacheEvict(value = "userCache", allEntries = true)
    public Object setRole(Long id, String roleId) throws Exception {
        UserParam.roleIdValidate(id,roleId);
        User user =userMapper.findById(id);
        if (user == null) {throw new EuqException("9999","用户ID错误");}
        user.setRoleId(roleId);
        userMapper.update(user);
        return null;
    }
}